package com.my.admin.api;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.tree.TreeUtil;
import com.my.admin.entity.Comment;
import com.my.admin.service.CommentService;
import com.my.admin.util.Rest;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@Api(value = "评论接口", tags = "评论接口")
@RestController
@RequestMapping("api")
@CrossOrigin
public class CommentApiController {

    @Autowired
    private CommentService service;

    @GetMapping("comment/{articleId}")
    public Rest get(@PathVariable Long articleId) {
        return Rest.ok().setData("comments", TreeUtil.build(service.getByArticleId(articleId), 0L, (comment, tree) -> {
            tree.setId(comment.getId());
            tree.setParentId(comment.getParentId());
            tree.putExtra("nickname", comment.getNickname());
            tree.putExtra("email", comment.getEmail());
            tree.putExtra("url", comment.getUrl());
            tree.putExtra("content", comment.getContent());
            tree.putExtra("systemType", comment.getSystemType());
            tree.putExtra("browserType", comment.getBrowserType());
            tree.putExtra("articleId", comment.getArticleId());
            tree.putExtra("replyCommentId", comment.getReplyCommentId());
            tree.putExtra("createTime", DateUtil.format(comment.getCreateTime(), "yyyy年MM月DD日 HH:mm:ss"));
            tree.putExtra("replyNickname", comment.getReplyNickname());
        }));
    }

    @PostMapping("comment")
    public Rest add(@RequestBody Comment comment) {
        if (service.save(comment)) {
            return Rest.ok("评论成功！");
        }
        return Rest.ok("评论失败！");
    }

}
